package Servlet;

import Utils.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/DeleteDataServlet")
public class DeleteDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String tableName = req.getParameter("tablename");
        String[] row = req.getParameterValues("row");
        Map<String, String> rows = new HashMap<String, String>();
        List<String> columnNames = DbUtil.getColumnCount(req, tableName);
        if (row != null && columnNames != null) {
            for (int i = 0; i < columnNames.size(); i++) {
                rows.put(columnNames.get(i), row[i]);
            }
        }

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DELETE FROM ").append(tableName).append(" WHERE ");

        for (Map.Entry<String, String> entry : rows.entrySet()) {
            sqlBuilder.append(entry.getKey()).append("=").append("?").append(" AND ");
        }

        sqlBuilder.delete(sqlBuilder.length() - 5, sqlBuilder.length() - 1);

        String sql = sqlBuilder.toString();
        System.out.println(sql);
        DbUtil.executeUpdate(req, resp, sql, rows.values().toArray());
        resp.sendRedirect("GetTableServlet?tableName=" + tableName);

    }

}
